Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: "",
    recoding: false,
    start: true,
    currentTime: '00:00',
    duration: '01:00',
    timer: null,
    num: 0,
    percent: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.request({
      url: 'http://localhost:1234/mdetail?id=' + options.id,
      method: "GET",
      header: {
        'content-type': "application/json"
      },
      success: res => {
        console.log(res.data[0]);
        this.setData({
          detail: res.data[0],
        })
      },
      fail: err => {
        console.log(err);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var that = this;
    //获取全局唯一的录音管理器 RecorderManager实例
    that.recorderManager = wx.getRecorderManager()
    that.recorderManager.onStop((res) => {
      that.setData({
        tempFilePath: res.tempFilePath // 文件临时路径
      })
      console.log('获取到文件：' + that.data.tempFilePath)
      const {
        tempFilePath
      } = res

      wx.saveFile({
        tempFilePath: tempFilePath,
        success: function (res) {
          // 保存成功，res.savedFilePath 是保存后的文件路径
          var savedFilePath = res.savedFilePath;
          console.log(savedFilePath)
          that.setData({
            show: true
          })
          wx.uploadFile({
            filePath: savedFilePath,
            name: 'file',
            url: `http://localhost:1234/imgvideo/together?imgName=${that.data.detail.image}`,
            success: (res) => {
              // console.log(res.data);
              that.setData({
                fileName: `${JSON.parse(res.data).fileName}`
              })
            },
            fail: res => {
              console.log('fail')
            }
          })
        },
        fail: function (res) {
          console.log(res);
        }
      });
    })
    this.recorderManager.onError((res) => {
      console.log('录音失败了！')
    })
  },

  recode: function () {
    this.setData({
      recoding: !this.data.recoding
    })
    if (this.data.recoding && this.data.start) {
      this.countDown()
      this.setData({
        start: false
      })
      console.log('start')
      this.recorderManager.start({
        duration: 60000,
        sampleRate: 16000, //采样率，有效值 8000/16000/44100
        numberOfChannels: 1, //录音通道数，有效值 1/2
        encodeBitRate: 96000, //编码码率
        format: 'mp3', //音频格式，有效值 aac/mp3
        frameSize: 50, //指定帧大小
        audioSource: 'auto' //指定录音的音频输入源，可通过 wx.getAvailableAudioSources() 获取
      })
      this.videoContext.play();
    } else if (this.data.recoding && !this.data.start) {
      console.log('resume')
      this.countDown();
      this.recorderManager.resume()
      this.videoContext.play();
    } else {
      console.log('pause')
      // this.countDown();
      clearInterval(this.data.timer);
      this.setData({
        timer: null
      })
      this.recorderManager.pause()
      this.videoContext.pause();
    }
  },

  //点击完成
  finished: function () {
    clearInterval(this.data.timer);
    // this.countDown('finish')
    this.setData({
      timer: null,
      recoding: false
    })
    console.log('stop')
    this.videoContext.pause()
    this.recorderManager.stop()
  },

  //重录
  again: function () {
    clearInterval(this.data.timer);
    // this.countDown('again');
    this.onLoad();
    this.setData({
      timer: null,
      num: 0,
      recoding: false,
      start: true
    })
    this.videoContext.seek(0)
    this.videoContext.stop()
    this.setData({
      percent: 0,
      currentTime: '00:00'
    })
  },

  getUserInfo(event) {
    console.log(event.detail);
    wx.navigateTo({
      url: `../publish/publish?fileName=${this.data.fileName}`
    })
  },

  onClose() {
    this.setData({ close: false });
  },

  countDown: function (value) {
    this.data.timer = setInterval(() => {
      this.setData({
        num: this.data.num + 1
      })
      console.log(this.data.num);
      let currentTime = Math.floor(this.data.num)
      let minutes = Math.floor(currentTime / 60)
      let seconds = Math.floor(currentTime % 60)
      let time = ''
      if (minutes < 10 && seconds < 10) {
        time = `0${minutes}:0${seconds}`
      }
      else if (minutes >= 10 && seconds < 10) {
        time = `${minutes}:0${seconds}`
      }
      else if (minutes < 10 && seconds >= 10) {
        time = `0${minutes}:${seconds}`
      }
      else {
        time = `${minutes}:${seconds}`
      }
      this.setData({
        currentTime: time,
        percent: (this.data.num / 60) * 100
      })
      if (this.data.num > 60) {
        clearInterval(this.data.timer);
        this.recorderManager.pause()
        this.videoContext.pause();
        this.setData({
          timer: null
        })
        return;
      }
      // this.setData({
      //   currentTime: this.data.seconds
      // });
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
